// #ifdef H5
import WechatJSSDK from "jweixin-module";
import {
	goNav
} from "@/lib/Comment.js"

import {
	getWechatConfig,
} from "@/api/public";
import {
	WX_AUTH,
	STATE_KEY,
	LOGINTYPE,
	BACK_URL
} from '@/config/cache';
import {
	parseQuery
} from '@/util';
import store from '@/store';
import Cache from '@/util/cache';

import {
	wechatLogin
} from '@/api/user.js'

class AuthWechat {

	constructor() {
		//微信实例化对象
		this.instance = WechatJSSDK;
		//是否实例化
		this.status = false;

		this.initConfig = null;

	}


	/**
	 * 初始化wechat(分享配置)
	 */
	wechat() {
		return new Promise((resolve, reject) => {
			// if (this.status && !this.isAndroid()) return resolve(this.instance);
			if (!this.status) {

				getWechatConfig()
					.then(res => {
						
						this.instance.config(res.data);
						this.initConfig = res.data;
						this.status = true;
						this.instance.ready(() => {

							resolve(this.instance);
						})
					}).catch(err => {
						this.status = false;
						reject(err);
					});
			} else {
				resolve(this.instance);
			}
		});
	}

	signLink() {
		return window.location.href.split('#')[0]
	}

	/**
	 * 验证是否初始化
	 */
	verifyInstance() {
		let that = this;
		return new Promise((resolve, reject) => {
			if (that.instance === null && !that.status) {
				that.wechat().then(res => {
					resolve(that.instance);
				}).catch(() => {
					return reject();
				})
			} else {
				return resolve(that.instance);
			}
		})
	}
	// 微信公众号的共享地址
	openAddress() {
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.openAddress).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	}

	// 获取经纬度；
	location() {
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.getLocation, {
					type: 'wgs84'
				}).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	}

	// 使用微信内置地图查看位置接口；
	seeLocation(config) {
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.openLocation, config).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	}



	/**
	 * 微信支付
	 * @param {Object} config
	 */
	pay(config) {
		return new Promise((resolve, reject) => {
			this.wechat().then((wx) => {
				this.toPromise(wx.chooseWXPay, config).then(res => {
					resolve(res);
				}).catch(res => {
					reject(res);
				});
			}).catch(res => {
				reject(res);
			});
		});
	}

	share(d) {

		let that = this
		return new Promise((resolve, reject) => {

			that.wechat().then(wx => {
				wx.updateAppMessageShareData({
					title: d.title, // 分享标题
					desc: d.desc, // 分享描述
					link: d.link,//'http://lg.weimahulian.com/static/h5/index.html/#/pages/sub/hotel/userShape?key=a209ec41c33b4029ae148067ee7f6cae', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl:d.imgUrl, // 分享图标
					success: function() {
					
						// 设置成功
						resolve()
					},
					fail: function(err){
						uni.showToast({
							title:'分享失败>>>>>'+JSON.stringify(err),
							icon:'none',
							duration:5000
								
						})
					}
				})
				// that.toPromise(wx.onMenuShareAppMessage, d).then(res => {
				// 	console.log("分享成功", JSON.stringify(res))
				//                 uni.showToast({
				//                 	title:"分享成功"+JSON.stringify(d)
				//                 })
				// 	resolve(res);
				// }).catch(err => {

				// 	console.log("分享失败222", JSON.stringify(err))
				// 	reject(err);
				// });
			}).catch(err => {

				reject(err);
			})
		});
	}

	scan() {


		return new Promise((resolve, reject) => {
			this.wechat().then((wx) => {
				this.toPromise(wx.scanQRCode, {
					desc: 'scanQRCode desc',
					needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
					scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有					
				}).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});

	}

	toPromise(fn, config = {}) {
		return new Promise((resolve, reject) => {
			fn({
				...config,
				success(res) {
					resolve(res);
				},
				fail(err) {
					reject(err);
				},
				complete(err) {
					reject(err);
				},
				cancel(err) {
					reject(err);
				}
			});
		});
	}

	/**
	 * 自动去授权
	 */
	oAuth(snsapiBase, url) {
		if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
		const {
			code
		} = parseQuery();
		if (!code) {
			return this.toAuth(snsapiBase, url);
		} else {
			wechatLogin(code).then(res => {
				store.commit("LOGIN", res.data);
				let back = store.getters.backUrl
				back = location.protocol+"//"+ location.host+location.pathname+'#'+back
				store.commit("SETBACKURL",'');
				//goNav(back)
				location.href =back; //location.pathname
			}).catch(err => {
				uni.showToast({
					title: "登录失败!",
					icon: "none"
				})
			})
		}
	}

	clearAuthStatus() {

	}

	/**
	 * 授权登陆获取token
	 * @param {Object} code
	 */
	auth(code) {
		return new Promise((resolve, reject) => {
			let loginType = Cache.get(LOGINTYPE);

		});
	}

	/**
	 * 获取跳转授权后的地址
	 * @param {Object} appId
	 */
	getAuthUrl(appId, snsapiBase, backUrl) {
		const redirect_uri = encodeURIComponent(
			`${location.origin}${backUrl}?scope=${snsapiBase}&back_url=` +
			encodeURIComponent(
				encodeURIComponent(
					uni.getStorageSync(BACK_URL) ?
					uni.getStorageSync(BACK_URL) :
					location.pathname + location.search
				)
			)
		);
		console.log('redirect_uri', redirect_uri);
		uni.removeStorageSync(BACK_URL);
		const state = encodeURIComponent(
			("" + Math.random()).split(".")[1] + "authorizestate"
		);
		uni.setStorageSync(STATE_KEY, state);
		if (snsapiBase === 'snsapi_base') {
			return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
		} else {
			return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
		}

	}

	/**
	 * 跳转自动登陆
	 */
	toAuth(snsapiBase, backUrl) {
		let that = this;
		this.wechat().then(wx => {
			location.href = this.getAuthUrl(that.initConfig.appId, snsapiBase, backUrl);
		})
	}

	/**
	 * 绑定事件
	 * @param {Object} name 事件名
	 * @param {Object} config 参数
	 */
	wechatEvevt(name, config) {
		let that = this;
		return new Promise((resolve, reject) => {
			let configDefault = {
				fail(res) {
					console.log(res, 11111);
					if (that.instance) return reject({
						is_ready: true,
						wx: that.instance
					});
					that.verifyInstance().then(wx => {
						return reject({
							is_ready: true,
							wx: wx
						});
					})
				},
				success(res) {
					return resolve(res, 2222);
				}
			};
			Object.assign(configDefault, config);
			that.wechat().then(wx => {
				if (typeof name === 'object') {
					name.forEach(item => {
						wx[item] && wx[item](configDefault)
					})
				} else {
					wx[name] && wx[name](configDefault)
				}
			})
		});
	}


	

}

export default new AuthWechat();
// #endif
